package com.ksyun.campus.client.fetcher;

import com.google.gson.Gson;
import com.ksyun.campus.client.domain.DataServerMsg;
import com.ksyun.campus.client.domain.MetaServerMsg;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Component
public class MetaServiceFetcher {
    private ZooKeeper zooKeeper;
    public MetaServiceFetcher() throws IOException {
        this.zooKeeper = new ZooKeeper("localhost:2181", 3000, null);
    }

    //
    public MetaServerMsg getMetaServiceInfo(String path) {
        try {
            byte[] data = zooKeeper.getData(path, false, null);
            //获取为MetaServerMsg对象
            String jsonString = new String(data, StandardCharsets.UTF_8);
            // 使用 Gson 将 JSON 字符串反序列化为 MetaServerMsg 对象
            Gson gson = new Gson();
            return gson.fromJson(jsonString, MetaServerMsg.class);

        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
            return null;
        }
    }

    //输入DataServcer的路径值

    public List<DataServerMsg> getDataServer(String path){
        List<DataServerMsg> dataServer=new ArrayList<>();
        try {
            // 获取当前节点的子节点
            List<String> children = zooKeeper.getChildren(path, false);
            Gson gson=new Gson();
            for (String child : children) {
                String childPath = path + "/" + child;
                // 获取子节点的数据
                byte[] data = zooKeeper.getData(childPath, false, null);
                String dataString = new String(data, StandardCharsets.UTF_8);

                //封装dataServer的数据进行返回
                dataServer.add(gson.fromJson(dataString, DataServerMsg.class));
            }
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
        }
        return dataServer;
    }
    public void close() throws InterruptedException {
        zooKeeper.close();
    }
}
